// 用户认证服务
// 处理用户登录、注册、会话管理等功能

import { dataService } from './simpleDbService.js'
import { dbService } from './simpleDbService.js'

// 模拟API延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 用户认证服务
export const authService = {
  // 登录
  async login(username, password) {
    try {
      await delay(500)
      
      // 查找用户
      const user = dataService.users.findByUsername(username)
      
      if (!user) {
        throw new Error('用户不存在')
      }
      
      // 验证密码（实际项目中应该使用加密验证）
      if (user.password !== password) {
        throw new Error('密码错误')
      }
      
      // 保存用户会话
      const userSession = {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar,
        role: user.role || 'user',
        createdAt: user.createdAt
      }
      
      // 保存到localStorage
      localStorage.setItem('currentUser', JSON.stringify(userSession))
      localStorage.setItem('token', this.generateToken())
      
      return userSession
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  },
  
  // 注册
  async register(userData) {
    try {
      await delay(500)
      
      // 检查用户名是否已存在
      const existingUser = dataService.users.findByUsername(userData.username)
      if (existingUser) {
        throw new Error('用户名已存在')
      }
      
      // 检查邮箱是否已存在
      const existingEmail = dataService.users.findByEmail(userData.email)
      if (existingEmail) {
        throw new Error('邮箱已被注册')
      }
      
      // 创建新用户
      const newUser = {
        ...userData,
        role: 'user',
        avatar: userData.avatar || `https://placehold.co/50x50/667eea/FFFFFF?text=${userData.username.charAt(0).toUpperCase()}`,
        followers: 0,
        following: 0,
        uploads: 0,
        favorites: [],
        history: [],
        settings: {
          notifications: true,
          darkMode: false,
          autoPlay: true
        }
      }
      
      // 保存到数据库
      const createdUser = dataService.users.create(newUser)
      
      // 自动登录
      return this.login(userData.username, userData.password)
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  },
  
  // 登出
  logout() {
    localStorage.removeItem('currentUser')
    localStorage.removeItem('token')
    localStorage.removeItem('adminLoggedIn')
    localStorage.removeItem('adminUser')
  },
  
  // 获取当前用户
  getCurrentUser() {
    const userJson = localStorage.getItem('currentUser')
    return userJson ? JSON.parse(userJson) : null
  },
  
  // 检查是否已登录
  isLoggedIn() {
    return !!this.getCurrentUser()
  },
  
  // 检查是否为管理员
  isAdmin() {
    const user = this.getCurrentUser()
    return user && (user.role === 'admin' || user.role === 'superadmin')
  },
  
  // 更新用户信息
  async updateProfile(userId, profileData) {
    try {
      await delay(300)
      
      // 删除敏感字段
      delete profileData.password
      delete profileData.role
      
      const updatedUser = dataService.users.update(userId, profileData)
      
      // 更新当前会话
      const currentUser = this.getCurrentUser()
      if (currentUser && currentUser.id === userId) {
        const updatedSession = {
          ...currentUser,
          ...profileData
        }
        localStorage.setItem('currentUser', JSON.stringify(updatedSession))
      }
      
      return updatedUser
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  },
  
  // 修改密码
  async changePassword(userId, currentPassword, newPassword) {
    try {
      await delay(300)
      
      // 获取用户
      const user = dataService.users.getById(userId)
      
      if (!user) {
        throw new Error('用户不存在')
      }
      
      // 验证当前密码
      if (user.password !== currentPassword) {
        throw new Error('当前密码错误')
      }
      
      // 更新密码
      await dataService.users.update(userId, { password: newPassword })
      
      return true
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    }
  },
  
  // 生成模拟token
  generateToken() {
    return 'token_' + Date.now() + '_' + Math.random().toString(36).substr(2)
  },
  
  // 刷新token
  refreshToken() {
    const user = this.getCurrentUser()
    if (user) {
      localStorage.setItem('token', this.generateToken())
      return true
    }
    return false
  }
}

// 导出默认服务
export default authService